<?php
declare (strict_types = 1);

namespace app\common\customer\model;

use app\common\config\logic\DictionaryLogic;
use app\common\config\model\ConfigStatus;
use app\common\system\logic\UserLogic;
use think\Model;
use think\model\concern\SoftDelete;

class CustomerVisit extends Model
{
    protected $table = "tk_member_visit";
    
    use SoftDelete;
    protected $defaultSoftDelete = 0;

    protected $type = [
        'next_visit_time' => 'timestamp',
        'files' => 'json',
    ];

    public function getFilesAttr($value) {
        // 如果为空,则返回空数组
        if (empty($value)) return [
            'images' => [],
            'files' => [],
        ];

        $data = json_decode($value, true);
        // 根据url 获取files里的所有图片
        $images = [];
        $files = [];
        foreach ($data as $file) {
            if (empty($file['url'])) continue;
            // 如果$file['url']是图片,则添加到images中
            // 以http或者https开头,jpg|jpeg|png|gif|bmp|webp文件,不区分大小写
            if (preg_match("/^(http|https):\/\/.*\.(jpg|jpeg|png|gif|bmp|webp)\.*/i", $file['url'])) {
                $images[] = $file;
            } else {
                $files[] = $file;
            }
        }

        $group = [
            'images' => $images,
            'files' => $files,
        ];

        return $group;
    }

    public function tags(){
        // 使用fields时需要注意,必须包含visit_id, 因为是通过这个参数进行比对的
        return $this->hasMany(CustomerTag::class, "visit_id", "id")->field("id,visit_id,product_id,status");
    }

    public function getUserAttr($value, $data) {
        $userLogic = new UserLogic();
        $user = $userLogic->getUser($data['user_id']);

        return $user;
    }

    public function getStatusTitleAttr($value, $data) {
        $dictionaryLogic = new DictionaryLogic();
        $row = $dictionaryLogic->getItem($data['status'], ConfigStatus::class, ['id','title']);

        return empty($row) ? "未跟进" : $row['title'];
    }
}
